const app = getApp()
let qCloud = require("../../index.js");

Page({
  /** 页面的初始数据 */
  data: {
    imgPath: qCloud.config.STATIC_IMAGE_PATH,
    goodsId: null, // 货物ID
    goodsName: "", // 货物名称(货号)
    goodsCode: "", // 货物编号(编号)
    cooperateEnterpriseId: 0, // 合作企业
    cooperateEnterpriseName: "", // 合作企业名称
    warehouseId: 0, // 仓库ID
    warehouseName: "", // 仓库名称
    warehouseList: [], // 仓库列表
    goodsShelves: "", // 货架号
    warehouseInManner: "", // 入库方式
    warehouseInMannerTitle: "", // 入库方式名称
    warehouseInMannerList: [], // 入库方式列表
    inboundTotal: 0, // 入库总数
    showSpecsTypeModal: false, // 尺码类型标记
    specsTypeList: [], // 尺码类型列表-
    specsType: "", // 尺码类型
    specsTypeTitle: "", // 尺码类型
    imageId: "", // 图片
    imageUrl: "", // 图片
    showImg: false, // 是否显示图片上传组件
    remark: "", // 备注

    showModalStatus: false,
    cooperateEnterpriseList: [],
  },
  // 所属仓库
  warehouseChange(e) {
    let self = this;
    let index = e.detail.value;
    let warehouseList = self.data.warehouseList;
    self.setData({
      warehouseId: warehouseList[index].id, // 仓库ID
      warehouseName: warehouseList[index].title, // 仓库名称
    });
  },
  // 货架号
  goodsShelvesInput(e) {
    let self = this;
    self.setData({
      goodsShelves: e.detail.value.trim()
    });
  },
  // 入库方式
  warehouseInMannerChange(e) {
    let self = this;
    let index = e.detail.value;
    let warehouseInMannerList = self.data.warehouseInMannerList;
    self.setData({
      warehouseInManner: warehouseInMannerList[index].id, // 入库方式
      warehouseInMannerTitle: warehouseInMannerList[index].title, // 入库方式名称
    });
  },
  // 计算入库数量
  countInboundTotal() {
    let self = this;
    let inboundTotal = 0;

    let specsTypeList = self.data.specsTypeList;
    for (let i = 0; i < specsTypeList.length; i++) {
      let specsType = specsTypeList[i];
      for (let j = 0; j < specsType.specsList.length; j++) {
        let specsInfo = specsType.specsList[j];
        inboundTotal = inboundTotal * 1 + specsInfo.inboundQuantity * 1
      }
    }

    self.setData({
      inboundTotal: inboundTotal
    });
  },
  // 删除尺码类型
  delSpecsType(e) {
    let self = this;
    let index = e.currentTarget.dataset.index;
    let specsTypeList = self.data.specsTypeList;
    specsTypeList.splice(index, 1);

    self.setData({
      specsTypeList: specsTypeList
    });

    // 计算入库数量
    self.countInboundTotal();
  },
  // 尺码数量
  inboundQuantityInput(e) {
    let self = this;
    let inboundQuantity = e.detail.value; // 数量
    let index = e.currentTarget.dataset.index;
    let stIndex = e.currentTarget.dataset.stindex;
    let specsTypeList = self.data.specsTypeList;
    specsTypeList[index].specsList[stIndex]["inboundQuantity"] = inboundQuantity.trim();

    let unitPrice = specsTypeList[index].specsList[stIndex]["unitPrice"]; // 单价
    specsTypeList[index].specsList[stIndex]["totalPrice"] = inboundQuantity * unitPrice; // 总价 = 数量 * 单价

    self.setData({
      specsTypeList: specsTypeList
    });

    // 计算入库数量
    self.countInboundTotal();
  },


  // 查找企业
  searchEnterprise() {
    let params = {}
    this.queryCooperateEnterpriseList(params);

    let animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    });

    this.animation = animation;
    animation.translateY(300).step();
    this.setData({
      animationData: animation.export(),
      showModalStatus: true
    });
    setTimeout(function () {
      animation.translateY(0).step();
      this.setData({
        animationData: animation.export()
      });
    }.bind(this), 200);
  },

  hideEnterpriseModal: function (e) {
    let animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    });
    this.animation = animation;
    animation.translateY(300).step();
    this.setData({
      animationData: animation.export(),
    });
    setTimeout(function () {
      animation.translateY(0).step();
      this.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(this), 200);

    this.setData({
      cooperateEnterpriseList: []
    })
  },

  searchInput: function (e) {
    let self = this;
    let params = {
      enterpriseName: e.detail.value
    };
    this.queryCooperateEnterpriseList(params);
  },

  // 确认选择企业
  confirmEnterprise(e) {
    let index = e.currentTarget.dataset.index;
    this.setData({
      cooperateEnterpriseId: this.data.cooperateEnterpriseList[index].cooperateEnterpriseId,
      cooperateEnterpriseName: this.data.cooperateEnterpriseList[index].cooperateEnterpriseName,
      showModalStatus: false
    })
  },

  // 查询合作企业列表
  queryCooperateEnterpriseList(params) {
    let self = this;
    app.fetchApis(self, qCloud.api.common_queryCooperateEnterpriseList, params, "POST", function (e) {
      let result = e.data;
      if (result.code == 200) {
        let data = result.data;
        self.setData({
          cooperateEnterpriseList: data.enterpriseList
        });
      }
    });
  },

  // 尺码单价
  unitPriceInput(e) {
    let self = this;
    let unitPrice = e.detail.value; // 单价
    let index = e.currentTarget.dataset.index;
    let stIndex = e.currentTarget.dataset.stindex;
    let specsTypeList = self.data.specsTypeList;
    specsTypeList[index].specsList[stIndex]["unitPrice"] = unitPrice.trim();

    let inboundQuantity = specsTypeList[index].specsList[stIndex]["inboundQuantity"]; // 数量
    specsTypeList[index].specsList[stIndex]["totalPrice"] = inboundQuantity * unitPrice; // 总价 = 数量 * 单价

    self.setData({
      specsTypeList: specsTypeList
    });
  },
  // 删除尺码
  delSpecs(e) {
    let self = this;
    let index = e.currentTarget.dataset.index;
    let stIndex = e.currentTarget.dataset.stindex;
    let specsTypeList = self.data.specsTypeList;
    specsTypeList[index]["specsList"].splice(stIndex, 1);

    self.setData({
      specsTypeList: specsTypeList
    });

    // 计算入库数量
    self.countInboundTotal();
  },

  // 图片
  chooseImage() {
    let self = this;
    wx.chooseMedia({
      count: 1,
      mediaType: ["image"],
      sourceType: ["album", "camera"],
      maxDuration: 30,
      camera: "back",
      success(res) {
        wx.uploadFile({
          url: qCloud.api.uploadFile,
          filePath: res.tempFiles[0].tempFilePath,
          name: "file",
          formData: {
            "file": res.tempFiles[0].tempFilePath,
            "fileType": "6"
          },
          header: qCloud.buildSessionHeader(),
          success(response) {
            let resJson = JSON.parse(response.data);
            if (resJson.code == 200) {
              self.setData({
                imageId: resJson.data.filesId,
                imageUrl: resJson.data.filesUrl,
                showImg: true
              });
            }
          },
          fail(error) {
            wx.showToast({
              title: error,
              icon: "error"
            })
          }
        })
      },
      fail(e) {}
    });
  },

  // 备注
  remarkInput(e) {
    let self = this;
    self.setData({
      remark: e.detail.value.trim()
    });
  },

  /** 生命周期函数--监听页面加载 */
  onLoad: function (options) {
    let self = this;
    self.setData({
      goodsId: options.goodsId
    });

    // 初始化入库方式列表
    self.initWarehouseInMannerList();
    // 查询仓储货物详情
    self.queryGoodsDetails();
  },

  // 初始化入库方式列表
  initWarehouseInMannerList() {
    let warehouseInMannerList = [{
      id: "1",
      title: "生产入库"
    }, {
      id: "2",
      title: "退货入库"
    }, {
      id: "3",
      title: "采购入库"
    }];
    let self = this;
    self.setData({
      warehouseInMannerList: warehouseInMannerList,
    });
  },

  /** 查询仓储货物详情 */
  queryGoodsDetails: function () {
    let self = this

    let params = {
      goodsId: self.data.goodsId
    }

    app.fetchApis(self, qCloud.api.warehouse_queryGoodsDetails, params, "POST", function (e) {
      let result = e.data;

      if (result.code == 200) {
        let data = result.data;

        self.setData({
          goodsName: data.goodsName, // 货物名称(货号)
          goodsCode: data.goodsCode, // 货物编号
          goodsShelves: data.goodsShelves, // 货架号
          inboundTotal: data.goodsTotalNumber, // 入库数量
          specsType: data.specsType, // 尺码类型
          warehouseId: data.warehouseId, // 仓库ID
          warehouseName: data.warehouseName, // 仓库名称
          imageId: data.imageId, // 图片
          remark: data.remark, // 备注
          cooperateEnterpriseId: data.cooperateEnterpriseId, // 合作企业ID
          cooperateEnterpriseName: data.cooperateEnterpriseName, // 合作企业名称
        });

        // 获取图片信息
        self.getFilesUrl(data.imageId);
        // 尺码类型列表
        self.convertSpecsTypeList(data.goodsSpecsList);
        // 尺码类型
        self.convertSpecsTypeTitle(data.specsType);

        // 查询仓库列表
        self.queryWarehouseList();
      }
    });
  },

  // 获取图片信息
  getFilesUrl: function (imageId) {
    let self = this;
    let params = {
      filesId: imageId
    }

    app.fetchApis(self, qCloud.api.getFileUrl, params, "GET", function (e) {
      let result = e.data;
      if (result.code == 200) {
        let data = result.data;
        self.setData({
          imageUrl: data.filesUrl,
          showImg: true
        });
      }
    });
  },

  /** 查询仓库列表 */
  queryWarehouseList: function () {
    let self = this;

    let params = {};

    app.fetchApis(self, qCloud.api.common_queryWarehouseList, params, "POST", function (e) {
      let result = e.data;

      if (result.code == 200) {
        let data = result.data;

        let warehouseName = "";
        let warehouseList = [];
        for (let i = 0; i < data.warehouseList.length; i++) {
          let warehouseInfo = data.warehouseList[i];
          for (let i = 0; i < warehouseInfo.subWarehouseList.length; i++) {
            let subWarehouseInfo = warehouseInfo.subWarehouseList[i];
            let warehouse = {
              id: subWarehouseInfo.warehouseId,
              title: warehouseInfo.warehouseName + ":" + subWarehouseInfo.warehouseName,
            };
            warehouseList.push(warehouse);

            if (self.data.warehouseId == subWarehouseInfo.warehouseId) {
              warehouseName = warehouseInfo.warehouseName + " : " + subWarehouseInfo.warehouseName;
            }
          }
        }

        self.setData({
          warehouseName: warehouseName,
          warehouseList: warehouseList
        });
      }
    });
  },

  // 转换尺码类型列表
  convertSpecsTypeList(goodsSpecsList) {
    let self = this;

    let specsTypeList = [];
    let colourIndex = [];
    for (let i = 0; i < goodsSpecsList.length; i++) {
      let goodsSpecs = goodsSpecsList[i];

      if (colourIndex.length > 0) {
        let ci = -1;
        for (let j = 0; j < colourIndex.length; j++) {
          if (goodsSpecs.colour == colourIndex[j]) {
            ci = j;
            break;
          }
        }

        if (ci == -1) {
          colourIndex.push(goodsSpecs.colour);

          let specsList = [{
            goodsSpecsId: goodsSpecs.goodsSpecsId,
            specs: goodsSpecs.specs,
            inboundQuantity: goodsSpecs.inventory,
            unitPrice: goodsSpecs.unitPrice,
            totalPrice: goodsSpecs.totalPrice,
          }];
          let specsTypeInfo = {
            colour: goodsSpecs.colour,
            specsList: specsList
          };
          specsTypeList.push(specsTypeInfo);
        } else {
          let specsInfo = {
            goodsSpecsId: goodsSpecs.goodsSpecsId,
            specs: goodsSpecs.specs,
            inboundQuantity: goodsSpecs.inventory,
            unitPrice: goodsSpecs.unitPrice,
            totalPrice: goodsSpecs.totalPrice,
          };
          specsTypeList[ci]["specsList"].push(specsInfo);
        }
      } else {
        colourIndex.push(goodsSpecs.colour);

        let specsList = [{
          goodsSpecsId: goodsSpecs.goodsSpecsId,
          specs: goodsSpecs.specs,
          inboundQuantity: goodsSpecs.inventory,
          unitPrice: goodsSpecs.unitPrice,
          totalPrice: goodsSpecs.totalPrice,
        }];
        let specsTypeInfo = {
          colour: goodsSpecs.colour,
          specsList: specsList
        };
        specsTypeList.push(specsTypeInfo);
      }
    }

    self.setData({
      specsTypeList: specsTypeList // 尺码类型列表
    });
  },

  // 转换尺码类型
  convertSpecsTypeTitle(specsType) {
    let self = this;
    let specsTypeTitle = "";
    if (specsType == "SML") {
      specsTypeTitle = "SML尺码";
    } else if (specsType == "NS") {
      specsTypeTitle = "数字尺码";
    } else if (specsType == "CS") {
      specsTypeTitle = "自定义尺码";
    }
    self.setData({
      specsTypeTitle: specsTypeTitle
    });
  },

  // 入库
  submitWarehouseIn() {
    let self = this;

    let title = self.checkParams();
    if (title != "") {
      wx.showToast({
        title: title,
        icon: "error"
      });
      return;
    }

    let specsList = []; // 规格列表
    let specsTypeList = self.data.specsTypeList;
    for (let i = 0; i < specsTypeList.length; i++) {
      let specsType = specsTypeList[i];
      for (let j = 0; j < specsType.specsList.length; j++) {
        let specsInfo = specsType.specsList[j];
        let specs = { // 规格
          goodsSpecsId: specsInfo.goodsSpecsId, // 货物规格ID:已存在货物规格增加入库数量时必送
          colour: specsType.colour, // 颜色
          specs: specsInfo.specs, // 尺码
          inboundQuantity: specsInfo.inboundQuantity, // 入库数量
          unitPrice: specsInfo.unitPrice, // 单价
          totalPrice: specsInfo.totalPrice, // 总价
        };
        specsList.push(specs);
      }
    }

    if (specsList.length > 0) {
      let params = {
        mark: "2", // 1-入库;2-货物入库;3-生产入库;
        warehouseId: self.data.warehouseId, // 仓库ID
        goodsId: self.data.goodsId, // 货物ID:已存在货物增加入库数量时必送
        goodsName: self.data.goodsName, // 货物名称
        goodsCode: self.data.goodsCode, // 货物编号
        goodsShelves: self.data.goodsShelves, // 货架号
        warehouseInManner: self.data.warehouseInManner, // 入库方式
        specsType: self.data.specsType, // 尺码类型
        inboundTotal: self.data.inboundTotal, // 入库总数
        cooperateEnterpriseId: self.data.cooperateEnterpriseId, // 合作企业
        cooperateEnterpriseName: self.data.cooperateEnterpriseName, // 合作企业名称
        imageId: self.data.imageId, // 图片
        remark: self.data.remark, // 备注
        specsList: specsList, // 规格列表
      }

      app.fetchApis(self, qCloud.api.warehouse_submitWarehouseIn, params, "POST", function (e) {
        let result = e.data;

        if (result.code == 200) {
          wx.navigateTo({
            url: "/pages/warehouse/index",
          });
        }
      });
    } else {
      wx.showToast({
        title: "请输入规格信息",
        icon: "error"
      });
    }
  },
  // 校验参数
  checkParams() {
    let self = this;
    if (self.data.warehouseId == 0) {
      return "请选择仓库";
    }
    if (self.data.warehouseInManner == "") {
      return "请选择入库方式";
    }
    return "";
  },
  /** 生命周期函数--监听页面初次渲染完成 */
  onReady: function () {},
  /** 生命周期函数--监听页面显示 */
  onShow: function () {},
  /** 生命周期函数--监听页面隐藏 */
  onHide: function () {},
  /** 生命周期函数--监听页面卸载 */
  onUnload: function () {},
  /** 页面相关事件处理函数--监听用户下拉动作 */
  onPullDownRefresh: function () {},
  /** 页面上拉触底事件的处理函数 */
  onReachBottom: function () {},
  /** 用户点击右上角分享 */
  onShareAppMessage: function () {}
});
